//1.引入相关模块
import http = require("http")
import url = require("url")
import { HandleManager } from "../handle/handleManager"
import{Delay} from "../task/delay"

export class WebServer
{
    static serverHttp: http.Server | null = null;
    static async listen(port: number): Promise<boolean>
    {
        WebServer.serverHttp = http.createServer(WebServer.onHttp);
        let inited=false;
        WebServer.serverHttp.listen(port, () =>
        {
            inited=true;
            console.log("hello server on " + port);
        });
  
        while(inited==false)
        {
            await Delay(100);
        }
        return true;
    }
    private static onHttp(req: http.IncomingMessage, res: http.ServerResponse): void
    {
        var urlstr: string = "";

        if (req.url != null)
        {
            urlstr = req.url;
        }
        //req是请求 
        var _url: url.UrlWithParsedQuery = url.parse(urlstr, true);
        if (_url.pathname != null)
        {//找到其它的处理器
            var handleobj = HandleManager.GetHandle(_url.pathname);
            if (handleobj != null)
            {
                try
                {
                    var bPost = req.method == "POST";
                    if (bPost)
                        handleobj.onPost(req, res);
                    else
                        handleobj.onGet(_url.query, res);
                }
                catch (err)
                {
                    let errstr: string;
                    if (err instanceof Error)
                    {
                        errstr = (err as Error).message;
                    }
                    else
                    {
                        errstr = JSON.stringify(err);
                    }
                    res.writeHead(200, { 'Content-Type': 'text/html' });
                    res.write('error in handle:' + _url.pathname + "  " + JSON.stringify(_url.query) + "  Error" + errstr);
                    res.end();
                }
                finally
                {
                    return;
                }
            }
        }
        //找不到就走这条路
        //_url.pathname是请求的相对路径，可以根据这个分配给不同的http请求
        //req.method req.method is get or post

        res.writeHead(200, { 'Content-Type': 'text/html' });
        var bPost = req.method == "POST";
        res.write('Hello Http Server:' + _url.pathname + "  " + bPost + "  " + JSON.stringify(_url.query));
        res.end();
    }
}


